package com.wf.protobuf.netty;

import com.wf.protobuf.builder.ProtobufMsgBuilder;
import com.wf.protobuf.domain.ProtoMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * protobuf客户端
 *
 * @author wf
 * @since 2022/5/28
 */
@Slf4j
public class ProtobufClient {

    public void startClient() {
        NioEventLoopGroup loopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            ch.pipeline().addLast(new ProtobufEncoder());
                        }
                    });
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(8888)).sync();
            future.addListener((ChannelFutureListener) connectFutureListener -> {
                if (connectFutureListener.isSuccess()) {
                    log.info("客户端连接成功");
                }
            });
            future.sync();
            Channel channel = future.channel();
            String content = "testProtobufTransfer";
            for (int i = 0; i< 1000; i++) {
                ProtoMsg user = ProtobufMsgBuilder.buildMsg(i, i + "->" + content);
                channel.writeAndFlush(user);
                log.info("发送报文数：" + i);
            }
            channel.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            loopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ProtobufClient().startClient();
    }

}
